import axios from 'axios'
import { ES_CONFIG } from '@/config/elasticsearch'
import type { RowObject } from 'handsontable/common'

export interface CellMeta {
  backgroundColor?: string;
}

export interface TableMeta {
  cells: { [key: string]: CellMeta };
  columnWidths: { [key: number]: number };
}

export type TableData = Array<Array<string | number | null>> | RowObject[]

export interface ConfigData {
  data: TableData;
  metadata: TableMeta;
}

export interface ConfigDocument {
  id: number
  type: string
  data: string  // 改为string类型，因为我们存储JSON字符串
  timestamp: number  // 改为number类型，使用时间戳
}

// 页签配置接口
export interface TabConfig {
  id: string
  name: string
  label: string
  configType: ConfigType
  order: number
  isDefault?: boolean
  isRemovable?: boolean
}

// 页签配置文档接口
export interface TabConfigDocument {
  id: string
  tabs: TabConfig[]
  timestamp: number
}

export type ConfigType = 'talent_config' | 'control_buff_config' | string

const getCacheKey = (type: ConfigType) => `${type}_cache`
const getCacheTimestampKey = (type: ConfigType) => `${type}_cache_timestamp`
const CACHE_EXPIRE_TIME = 24 * 60 * 60 * 1000 // 24小时

/**
 * 初始化ES索引
 */
export const initializeESIndices = async () => {
  const indices = [ES_CONFIG.indices.talentConfig, ES_CONFIG.indices.controlBuffConfig]

  for (const index of indices) {
    try {
      // 检查索引是否存在
      const checkResponse = await axios.head(`${ES_CONFIG.baseUrl}/${index}`)
      if (checkResponse.status === 200) {
        console.log(`Index ${index} already exists`)
        continue
      }
    } catch (error) {
      // 索引不存在，创建新索引
      try {
        await axios.put(
          `${ES_CONFIG.baseUrl}/${index}`,
          {
            mappings: {
              properties: {
                id: { type: 'keyword' },
                type: { type: 'keyword' },
                data: {
                  type: 'keyword'  // 将整个数组作为JSON字符串存储
                },
                tabs: {
                  type: 'nested',
                  properties: {
                    id: { type: 'keyword' },
                    name: { type: 'keyword' },
                    label: { type: 'text' },
                    configType: { type: 'keyword' },
                    order: { type: 'integer' },
                    isDefault: { type: 'boolean' },
                    isRemovable: { type: 'boolean' }
                  }
                },
                timestamp: { type: 'date' }
              }
            }
          },
          {
            headers: {
              'Content-Type': 'application/json'
            }
          }
        )
        console.log(`Successfully created index ${index}`)
      } catch (createError) {
        console.error(`Failed to create index ${index}:`, createError)
        throw createError
      }
    }
  }
}

/**
 * 从缓存中获取数据
 */
const getFromCache = (type: ConfigType): { data: ConfigData | string | null, timestamp: string | null } => {
  try {
    const cacheKey = getCacheKey(type)
    const cacheTimestampKey = getCacheTimestampKey(type)
    const cachedData = localStorage.getItem(cacheKey)
    const cachedTimestamp = localStorage.getItem(cacheTimestampKey)

    if (!cachedData || !cachedTimestamp) {
      return { data: null, timestamp: null }
    }

    // 检查缓存是否过期
    const timestamp = parseInt(cachedTimestamp)
    const now = Date.now()
    if (now - timestamp > CACHE_EXPIRE_TIME) {
      clearCache(type)
      return { data: null, timestamp: null }
    }

    return {
      data: cachedData,
      timestamp: cachedTimestamp
    }
  } catch (error) {
    console.error('Failed to get from cache:', error)
    return { data: null, timestamp: null }
  }
}

/**
 * 更新缓存
 */
const updateCache = (type: ConfigType, data: string | any[][]): void => {
  try {
    const cacheKey = getCacheKey(type)
    const cacheTimestampKey = getCacheTimestampKey(type)
    const dataString = typeof data === 'string' ? data : JSON.stringify(data)
    localStorage.setItem(cacheKey, dataString)
    localStorage.setItem(cacheTimestampKey, Date.now().toString())  // 使用时间戳
  } catch (error) {
    console.error('Failed to update cache:', error)
  }
}

/**
 * 清除缓存
 */
export const clearCache = (type: ConfigType): void => {
  const cacheKey = getCacheKey(type)
  const cacheTimestampKey = getCacheTimestampKey(type)
  localStorage.removeItem(cacheKey)
  localStorage.removeItem(cacheTimestampKey)
}

/**
 * 获取ES索引名称
 */
const getESIndex = (type: ConfigType): string => {
  switch (type) {
    case 'talent_config':
      return ES_CONFIG.indices.talentConfig
    case 'control_buff_config':
      return ES_CONFIG.indices.controlBuffConfig
    default:
      // 对于动态配置类型，使用通用索引
      return ES_CONFIG.indices.talentConfig
  }
}

/**
 * 保存配置到ES
 */
export const esSaveConfig = async (type: ConfigType, configData: ConfigData): Promise<void> => {
  try {
    // 确保所有数据都是字符串
    const stringData = Array.isArray(configData.data[0])
      ? (configData.data as Array<Array<string | number | null>>).map(row =>
          row.map(cell => cell === null ? '' : String(cell))
        )
      : (configData.data as RowObject[]).map(row =>
          Object.values(row).map(cell => cell === null ? '' : String(cell))
        );

    // 只过滤掉末尾的空行，保留中间的空行
    let lastNonEmptyIndex = stringData.length - 1;
    while (lastNonEmptyIndex >= 0 && !stringData[lastNonEmptyIndex].some(cell => cell !== '')) {
      lastNonEmptyIndex--;
    }
    const filteredData = stringData.slice(0, lastNonEmptyIndex + 1);

    const payload = {
      type,
      data: JSON.stringify({
        data: filteredData,
        metadata: configData.metadata
      }),
      timestamp: Date.now()  // 使用时间戳
    }

    const response = await axios.post(
      `${ES_CONFIG.baseUrl}/${getESIndex(type)}/_doc`,
      payload,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (!response.data.result || !['created', 'updated'].includes(response.data.result)) {
      throw new Error('保存失败')
    }

    // 更新缓存
    updateCache(type, payload.data)
  } catch (error) {
    console.error(`Failed to save ${type}:`, error)
    throw error
  }
}

/**
 * 从ES获取最新的配置
 */
export const esGetLatestConfig = async (type: ConfigType, forceRefresh: boolean = false): Promise<ConfigData | null> => {
  try {
    // 如果不是强制刷新，先尝试从缓存获取
    if (!forceRefresh) {
      const { data: cachedData, timestamp: cachedTimestamp } = getFromCache(type)
      if (cachedData) {
        console.log('Using cached data from:', cachedTimestamp)
        return typeof cachedData === 'string' ? JSON.parse(cachedData) : cachedData
      }
    }

    // 强制刷新或缓存不存在/已过期，从ES获取
    const response = await axios.post(
      `${ES_CONFIG.baseUrl}/${getESIndex(type)}/_search`,
      {
        size: 1,
        query: {
          term: {
            type
          }
        },
        sort: [
          {
            timestamp: 'desc'
          }
        ]
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.data.hits.total.value === 0) {
      return null
    }

    const doc = response.data.hits.hits[0]._source as ConfigDocument
    const parsedData = JSON.parse(doc.data) // 解析存储的JSON字符串

    // 更新缓存
    updateCache(type, doc.data)

    return parsedData
  } catch (error) {
    console.error(`Failed to get latest ${type}:`, error)
    // 只有在非强制刷新时才尝试使用缓存数据
    if (!forceRefresh) {
      const { data: cachedData } = getFromCache(type)
      if (cachedData) {
        console.log('Using cached data after ES request failed')
        return typeof cachedData === 'string' ? JSON.parse(cachedData) : cachedData
      }
    }
    throw error
  }
}

// ========================= 页签配置管理 =========================

const TAB_CONFIG_CACHE_KEY = 'tab_config_cache'
const TAB_CONFIG_ID = 'talent_tabs_config'

/**
 * 获取默认页签配置
 */
export const getDefaultTabConfig = (): TabConfig[] => {
  return [
    {
      id: 'talent',
      name: 'talent',
      label: '天赋配置',
      configType: 'talent_config',
      order: 0,
      isDefault: true,
      isRemovable: false
    },
    {
      id: 'controlBuff',
      name: 'controlBuff',
      label: '控制BUFF配置',
      configType: 'control_buff_config',
      order: 1,
      isDefault: true,
      isRemovable: false
    }
  ]
}

/**
 * 保存页签配置到ES
 */
export const esSaveTabConfig = async (tabs: TabConfig[]): Promise<void> => {
  try {
    const payload: TabConfigDocument = {
      id: TAB_CONFIG_ID,
      tabs: tabs.sort((a, b) => a.order - b.order),
      timestamp: Date.now()
    }

    const response = await axios.post(
      `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.tabConfig}/_doc/${TAB_CONFIG_ID}`,
      payload,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (!response.data.result || !['created', 'updated'].includes(response.data.result)) {
      throw new Error('保存页签配置失败')
    }

    // 更新缓存
    localStorage.setItem(TAB_CONFIG_CACHE_KEY, JSON.stringify(payload))
  } catch (error) {
    console.error('Failed to save tab config:', error)
    throw error
  }
}

/**
 * 从ES获取页签配置
 */
export const esGetTabConfig = async (forceRefresh: boolean = false): Promise<TabConfig[]> => {
  try {
    // 如果不是强制刷新，先尝试从缓存获取
    if (!forceRefresh) {
      const cachedData = localStorage.getItem(TAB_CONFIG_CACHE_KEY)
      if (cachedData) {
        console.log('Using cached tab config')
        const parsed = JSON.parse(cachedData) as TabConfigDocument
        console.log('Using cached tab config')
        return parsed.tabs
      }
    }

    // 从ES获取
    const response = await axios.get(
      `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.tabConfig}/_doc/${TAB_CONFIG_ID}`,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.data.found) {
      console.log('load with remote database -> Found tab config')
      const doc = response.data._source as TabConfigDocument
      // 更新缓存
      localStorage.setItem(TAB_CONFIG_CACHE_KEY, JSON.stringify(doc))
      return doc.tabs.sort((a, b) => a.order - b.order)
    } else {
      // 如果没有找到配置，返回默认配置并保存
      const defaultTabs = getDefaultTabConfig()
      await esSaveTabConfig(defaultTabs)
      return defaultTabs
    }
  } catch (error) {
    console.error('Failed to get tab config:', error)
    // 如果获取失败，尝试使用缓存或返回默认配置
    if (!forceRefresh) {
      const cachedData = localStorage.getItem(TAB_CONFIG_CACHE_KEY)
      if (cachedData) {
        try {
          const parsed = JSON.parse(cachedData) as TabConfigDocument
          if (parsed.tabs && Array.isArray(parsed.tabs) && parsed.tabs.length > 0) {
            console.log('Using cached tab config after ES request failed')
            return parsed.tabs.sort((a, b) => a.order - b.order)
          }
        } catch (parseError) {
          console.error('Failed to parse cached tab config:', parseError)
        }
      }
    }
    // 最后返回默认配置并尝试保存（但不阻塞）
    const defaultTabs = getDefaultTabConfig()
    // 异步保存，不等待结果
    esSaveTabConfig(defaultTabs).catch(err => {
      console.warn('Failed to save default tab config:', err)
    })
    return defaultTabs
  }
}

/**
 * 添加新页签
 */
export const addNewTab = async (label: string, configType?: ConfigType): Promise<TabConfig[]> => {
  const tabs = await esGetTabConfig()
  const maxOrder = Math.max(...tabs.map(t => t.order), -1)

  const newTab: TabConfig = {
    id: `custom_${Date.now()}`,
    name: `custom_${Date.now()}`,
    label,
    configType: configType || `custom_config_${Date.now()}`,
    order: maxOrder + 1,
    isDefault: false,
    isRemovable: true
  }

  const updatedTabs = [...tabs, newTab]
  await esSaveTabConfig(updatedTabs)
  return updatedTabs
}

/**
 * 删除页签
 */
export const removeTab = async (tabId: string): Promise<TabConfig[]> => {
  const tabs = await esGetTabConfig()
  const tabToRemove = tabs.find(t => t.id === tabId)

  if (!tabToRemove) {
    throw new Error('页签不存在')
  }

  if (!tabToRemove.isRemovable) {
    throw new Error('该页签不能删除')
  }

  const updatedTabs = tabs.filter(t => t.id !== tabId)
  await esSaveTabConfig(updatedTabs)
  return updatedTabs
}

/**
 * 更新页签标签
 */
export const updateTabLabel = async (tabId: string, newLabel: string): Promise<TabConfig[]> => {
  const tabs = await esGetTabConfig()
  const tabIndex = tabs.findIndex(t => t.id === tabId)

  if (tabIndex === -1) {
    throw new Error('页签不存在')
  }

  tabs[tabIndex].label = newLabel
  await esSaveTabConfig(tabs)
  return tabs
}

/**
 * 重新排序页签
 */
export const reorderTabs = async (tabIds: string[]): Promise<TabConfig[]> => {
  const tabs = await esGetTabConfig()
  const reorderedTabs = tabIds.map((id, index) => {
    const tab = tabs.find(t => t.id === id)
    if (!tab) throw new Error(`页签 ${id} 不存在`)
    return { ...tab, order: index }
  })

  await esSaveTabConfig(reorderedTabs)
  return reorderedTabs
}

/**
 * 清除页签配置缓存
 */
export const clearTabConfigCache = (): void => {
  localStorage.removeItem(TAB_CONFIG_CACHE_KEY)
}
